<?php 

session_start();

require_once 'Zend/Loader.php';
include 'Zend/Gdata.php';
include 'Zend/Gdata/AuthSub.php';
include 'Zend/Gdata/Calendar.php';

if (!isset($_GET['token']))
{
	function getAuthSubUrl() 
	{
	  $next = 'http://www.club-connect.nl/hyvessync/authorization_step2.php';
	  $scope = 'http://www.google.com/calendar/feeds/';
	  $secure = false;
	  $session = true;
	  return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, 
		  $session);
	}
	
	$authSubUrl = getAuthSubUrl();
	$message = '<a href="'.$authSubUrl.'">login to your Google account</a>';
}
elseif(! isset($_SESSION['sessionToken']) && isset($_GET['token'])) 
{
  	
	$_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']); // Convert single-use token into a Session token
	$token = $_SESSION['sessionToken'];
	
	$gID = $_SESSION['gebruikersID'];
	// Write authorization header to database
	require_once("database_inc.php");
	$db = mysqli_connect($server,$gebruikersnaam,$password);
	mysqli_select_db($db, $database);
	$sql = "UPDATE users SET googleAuthSubToken = '$token' WHERE gebruikersID = '$gID'";
	mysqli_query($db, $sql);
	$message = '<a href="index1.php">Go back to gadget</a>';
	session_destroy();
	
}
else
{
	$message = 'You are already authenticated. <a href="index1.php">Go back to gadget</a>';
	session_destroy();
}


?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Authentication Google Calendar</title>
</head>

<body>
<div id="message">
<p><?php echo $message;?></p>
</div>
</body>
</html>